<?php

namespace app\common\logic;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Aliyun
{

    protected string $accessKeyId = '';  //  小程序appid
    protected string $accessKeySecret = ''; //  小程序secret

    public function __construct(string $accessKeyId = '', string $accessKeySecret = '')
    {
        $this->accessKeyId = $accessKeyId ?: config('aliyun.sms.accessKeyId');
        $this->accessKeySecret = $accessKeySecret ?: config('aliyun.sms.accessKeySecret');
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public function createClient()
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $this->accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $this->accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public function sendSms()
    {
        $client = $this->createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => "18317093686",
            "signName" => config('aliyun.sms.signName'),
            "templateCode" => config('aliyun.sms.templateCode'),
            "templateParam" => "{\"code\":\"1234\"}"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            halt($res);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
            return $error->message;
        }
    }
}